#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>

class InetAddr
{
private:
    void HostToNet()
    {
        bzero(&_addr, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &(_addr.sin_addr.s_addr));
    }
    void NetToHost()
    {
        _port = ntohs(_addr.sin_port);
        char inbuffer[64];
        inet_ntop(AF_INET, &(_addr.sin_addr.s_addr), inbuffer, sizeof(inbuffer));
        _ip = inbuffer;
    }

public:
    InetAddr() {}
    InetAddr(uint16_t port, std::string ip = "0.0.0.0")
        : _port(port), _ip(ip)
    {
        HostToNet();
    }
    InetAddr(const struct sockaddr_in &addr)
        : _addr(addr)
    {
        NetToHost();
    }
    struct sockaddr *Addr()
    {
        return (struct sockaddr *)&_addr;
    }
    socklen_t lenth()
    {
        return sizeof(_addr);
    }
    std::string ToString()
    {
        return _ip + "-" + std::to_string(_port);
    }
    void Init(const struct sockaddr_in &addr)
    {
        _addr = addr;
        NetToHost();
    }

private:
    struct sockaddr_in _addr;
    uint16_t _port;
    std::string _ip;
};